// @Author EthanScriptOn
// @Desc
package op_example

import (
	"errors"
	"fmt"
	"gitee.com/fatzeng/srf_switch_stream_bridge/framework/actuator"
	"gitee.com/fatzeng/srf_switch_stream_bridge/framework/operator"
)

type LoopDetectionMultiChannelDataOperator struct {
	operator.LoopMultiChannelDataOperator
}

func (l *LoopDetectionMultiChannelDataOperator) Execute(ctx *actuator.SrfSwitchBridgeActuatorContext, configIdentifier interface{}, structureParam interface{}) (resp interface{}, err error) {
	dataChan := make(chan interface{})
	config, ok := configIdentifier.(*operator.LoopMultiChannelDataOperatorConfig)
	if !ok {
		return nil, fmt.Errorf("configIdentifier is not LoopMultiChannelDataOperatorConfig")
	}
	operatorInstance := operator.GetOperator(config.GetOperatorIdentifier(false))
	extendInstance, ok := operatorInstance.(operator.LoopMultiChannelDataOperator)
	if !ok {
		return nil, fmt.Errorf("operator is not LoopMultiChannelDataOperator")
	}
	go func(dataChanTransmit chan interface{}, ctx *actuator.SrfSwitchBridgeActuatorContext, configIdentifierTransmit interface{}, paramsTransmit interface{}) {
		operatorIdentifier, err := extendInstance.GenerateUniqueIdentifier()
		if err != nil {
			_ = ctx.Record(actuator.OperatorExecute, fmt.Sprintf("generate unique identifier error: %s", err.Error()))
			return
		}
		defer operator.DestroyPipeline(operatorIdentifier)
		operator.SetPipeline(operatorIdentifier, dataChanTransmit)
		executeError := extendInstance.ExecuteWithLoop(ctx, configIdentifierTransmit, paramsTransmit)
		if executeError != nil {
			_ = ctx.Record(actuator.OperatorExecute, fmt.Sprintf("execute error: %s", executeError.Error()))
		}
	}(dataChan, ctx, configIdentifier, structureParam)
	return dataChan, nil
}

func (l *LoopDetectionMultiChannelDataOperator) GetDataPipeline(operatorIdentifier interface{}) chan<- interface{} {
	return operator.GetPipeline(operatorIdentifier)
}

func (l *LoopDetectionMultiChannelDataOperator) ExecuteWithLoop(ctx *actuator.SrfSwitchBridgeActuatorContext, operatorConfigIdentifier interface{}, structureParam interface{}) error {
	panic(errors.New("this function needs to be rewritten"))
}
